package com.hqyj.common.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * YanGG
 *
 * @ClassName: MyShiro
 * @author: yanguangzhi
 * @date: 2021/10/20 16:20
 */
@Configuration
public class MyShiro {
    /**
     * 配置密码匹配器
     *
     * @return
     */
    @Bean(name = {"hashedCred"})
    public HashedCredentialsMatcher getMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(1024);
        return matcher;
    }

    /**
     * 配置自定义的 realm
     *
     * @param matcher
     * @return
     */
    @Bean(name = {"myRealm"})
    public MyRealm getRealm(@Qualifier("hashedCred") HashedCredentialsMatcher matcher) {
        MyRealm realm = new MyRealm();
        realm.setCredentialsMatcher(matcher);
        return realm;
    }

    /**
     * 配置安全管理类
     *
     * @return
     */
    @Bean(name = {"securityManager"})
    public DefaultWebSecurityManager getSecurity(@Qualifier("myRealm") MyRealm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

//    @Bean
//    public LifecycleBeanPostProcessor getProcessor() {
//        return new LifecycleBeanPostProcessor();
//    }

    /**
     * html标签配置
     */
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

    /**
     * 配置权限
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilter(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);
        //配置登录页
        shiroFilter.setLoginUrl("/loginPage");
        //配置无权限访问页面
        shiroFilter.setUnauthorizedUrl("/noPower");
        //
        HashMap<String, String> map = new HashMap<>();

        map.put("/", "authc");

        map.put("/users", "roles[lv3]");
        shiroFilter.setFilterChainDefinitionMap(map);
        return shiroFilter;
    }
}
